﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pfz.Serialization
{
	/// <summary>
	/// Helper class for serializers. Generates the Id used to reference already serialized items.
	/// </summary>
	public sealed class DeserializationIdGenerator:
		IDisposable
	{
		internal DeserializationIdGenerator(ConfigurableSerializerBase serializer, Type type)
		{
			Serializer = serializer;
			
			if (!type.IsValueType)
				Id = serializer._idGenerator++;
		}
		/// <summary>
		/// Adds the given result to the already deserialized list (if possible).
		/// </summary>
		public void Dispose()
		{
			if (Result == null)
			{
				Serializer._idGenerator--;
				return;
			}

			if (!Result.GetType().IsValueType)
				Serializer._alreadyDeserialized.Add(Id, Result);
		}

		/// <summary>
		/// Gets the Serializer.
		/// </summary>
		public ConfigurableSerializerBase Serializer { get; private set; }

		/// <summary>
		/// Gets the generated Id.
		/// </summary>
		public int Id { get; private set; }

		/// <summary>
		/// Gets or sets the result. You must call this after deserializing the item.
		/// </summary>
		public object Result { get; set; }
	}
}
